package cn.fl.ref.fnccappayeeinfobig.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fnccappayeeinfobig.service.IFncCapPayeeInfoBigService;
import cn.fl.ref.fnccappayeeinfobig.util.JsonUtil;
import cn.fl.ref.fnccappayeeinfobig.vo.FncCapPayeeInfoBigVO;
import cn.fl.ref.fnccappayeeinfobig.vo.FncScmChrgParmBigVO;
import cn.fl.ref.fncprjbscinfo.service.IFncPrjBscInfoService;
import cn.fl.ref.fncprjbscinfo.service.IFncPrjPayPlanService;
import cn.fl.ref.fncprjbscinfo.util.UpbaaDate;
import cn.fl.ref.fncprjbscinfo.util.XirrData;
import cn.fl.ref.fncprjbscinfo.vo.FncPrjBscInfoVO;
import cn.fl.ref.fncprjbscinfo.vo.FncPrjPayPlanVO;
import cn.fl.ref.fncprjfstpyinfo.service.IFncPrjFstpyInfoService;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.ref.scmbaseinfo.service.IScmBaseInfoService;
import cn.fl.ref.scmbaseinfo.vo.ScmBaseInfoVO;
import cn.fl.system.constant.SysLogConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.ref.fnccappayeeinfobig.condition.FncCapPayeeInfoBigQueryCondition;
import fl.ref.fnccappayeeinfobig.constant.FncCapPayeeInfoBigConstant;
import fl.ref.fncprjbscinfo.condition.FncPrjBscInfoQueryCondition;
import fl.ref.fncprjbscinfo.condition.FncPrjPayPlanQueryCondition;
import fl.ref.fncprjfstpyinfo.condition.FncPrjFstpyInfoQueryCondition;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import fl.ref.scmbaseinfo.constant.ScmInfoConstant;

/**
 * @Description: 再融资大额付款
 */
@Controller
@RequestMapping("/rfbase/fncCapPayeeInfoBig")
public class FncCapPayeeInfoBigController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FncCapPayeeInfoBigController.class);

	@Autowired
	private IFncCapPayeeInfoBigService fncCapPayeeInfoBigService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	IFriBaseInfoService  friBaseInfoService;
	@Autowired
	IFncPrjBscInfoService  fncPrjBscInfoService;
	@Autowired
	private IScmBaseInfoService scmBaseInfoService;
	@Autowired
	private IFncPrjFstpyInfoService fncPrjFstpyInfoService;
	@Autowired
	IFncPrjPayPlanService  fncPrjPayPlanService;
	/**
	 * 跳转到列表页面
	 */
	@RequestMapping("/toListPage.do")
	public String toListPage(HttpServletRequest request) {

		// 付款类型(数据字典)
		request.setAttribute("payTypeList", sysDictionaryApiService.getKvList(FncCapPayeeInfoBigConstant.FNC_PAY_TYPE,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

		
		// 付款状态(数据字典)
		request.setAttribute("payStateList", sysDictionaryApiService.getKvList(FncCapPayeeInfoBigConstant.FNC_PAY_STATE,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

		request.setAttribute("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		
		//付款公司主体(数据字典 FNC0011)
		request.setAttribute("payerMainList", 
				sysDictionaryApiService.getKvList(FncCapPayeeInfoBigConstant.FNC_PAYER_MAIN,
						CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));
				
		return "rfbase/fncCapPayeeInfobig/fncCapPayeeInfoBigList";
	}

	/**
	 * 列表页面查询
	 */
	@RequestMapping("/initList.do")
	@ResponseBody
	public Object initList(FncCapPayeeInfoBigQueryCondition qc, HttpServletRequest request) {

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
//		if ("queryAll".equals(from)) {
//			//数据权限：查询所有
//		}else {
//			//数据权限：查询当前登录人所属事业部
//			qc.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
//		}
		if(qc.getPayerMain() != null) {
			qc.setPayerMain(qc.getPayerMain().trim());//去掉空格
		}
		qc.setIsDel(FncCapPayeeInfoBigConstant.IS_DEL_NO);
		page.setCondition(qc);

		Pager pager = this.fncCapPayeeInfoBigService.searchListPage(page);
		ListPageVO<FncCapPayeeInfoBigVO> listPage = new ListPageVO<FncCapPayeeInfoBigVO>(
				(List<FncCapPayeeInfoBigVO>) pager.getResultList(), pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page),
				CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 跳转到新增或修改页面
	 */
	@RequestMapping(value = "/toSave.do")
	public Object toSave(HttpServletRequest request) {

		request.setAttribute("operate", request.getParameter("operate"));

		// 付款类型(数据字典)
		request.setAttribute("payTypeList", sysDictionaryApiService.getKvList(FncCapPayeeInfoBigConstant.FNC_PAY_TYPE,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

//		// 付款账户(数据字典)
//		request.setAttribute("payerAccNoList", sysDictionaryApiService.getKvList(FncCapPayeeInfoBigConstant.FNC_PAYER_ACCNO,
//				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));
//
//		List<SysDictionaryDTO> sysDictionaryDTOList = sysDictionaryApiService.searchGroup(
//				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(),FncCapPayeeInfoBigConstant.FNC_PAYER_ACCNO);
//		BaseLogUtils.info(logger, null, "sysDictionaryDTOList:" + JSONObject.toJSONString(sysDictionaryDTOList),
//				CurrentThreadContext.getCurrentUserName());
		
		
		String id = (String) request.getParameter("id");
		if (StringUtils.isNotBlank(id)) {
			request.setAttribute("fncCapPayeeInfoBigVO", fncCapPayeeInfoBigService.selectById(Long.valueOf(id)));
		}
		request.setAttribute("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		request.setAttribute("loginUsrNm", CurrentThreadContext.getCurrentUserName());

		
		//计费信息-保证金到期处理方式
		List<KeyValueVO> mrgnUseMtdLst = sysDictionaryApiService.getKvList(ScmInfoConstant.FNC_SCM_CHRG_PARM_MRGN_USE_MTD, 
				CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		request.setAttribute("mrgnUseMtdJSON",JSONObject.toJSONString(mrgnUseMtdLst));
		
		//计费信息-费用名称列表
		List<KeyValueVO> feeList = sysDictionaryApiService.getKvList(ScmInfoConstant.FNC_SCM_FEE, 
				CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		request.setAttribute("feeListJSON", JSONObject.toJSONString(feeList));
		
		return "rfbase/fncCapPayeeInfobig/fncCapPayeeInfoBigSave";
	}

	/**
	 * 关联金融机构
	 */
	@RequestMapping("/getFriBaseInfoVOList.do")
	@ResponseBody
	public Object getFriBaseInfoVOList() {

		FriBaseInfoQueryCondition friBaseInfoQueryCondition = new FriBaseInfoQueryCondition();
		friBaseInfoQueryCondition.setInsSts(FriBaseInfoConstant.FRI_BASE_INFO_INS_STS_PASS);
		
		return friBaseInfoService.searchList(friBaseInfoQueryCondition);
	}
	
	/**
	 * 关联项目列表
	 */
	@RequestMapping("/getFncPrjIdList.do")
	@ResponseBody
	public Object getFncPrjIdList(String fundId) {

		if(StringUtils.isBlank(fundId)) return null;
		
		FncPrjBscInfoQueryCondition fncPrjBscInfoQueryCondition = new FncPrjBscInfoQueryCondition();
		fncPrjBscInfoQueryCondition.setIsdel(BaseConstant.IS_YESNO_NO);
		fncPrjBscInfoQueryCondition.setNotEqualFncprjstcd(14);//作废状态
		fncPrjBscInfoQueryCondition.setFncinsid(fundId);
		
		return fncPrjBscInfoService.searchList(fncPrjBscInfoQueryCondition);
	}
	
	
	/**
	 * 关联项目详情
	 */
	@RequestMapping("/getFncPrjBscInfo.do")
	@ResponseBody
	public Object getFncPrjBscInfo(Long fncPrjId) {

		if(fncPrjId == null) return null;
		FncPrjBscInfoVO fncPrjBscInfoVO = fncPrjBscInfoService.selectById(fncPrjId);
		if(fncPrjBscInfoVO != null && fncPrjBscInfoVO.getFncscmid() != null) {
			ScmBaseInfoVO scmBaseInfoVO = scmBaseInfoService.selectById(fncPrjBscInfoVO.getFncscmid());
			if(scmBaseInfoVO != null) {
				fncPrjBscInfoVO.setFncscmNM(scmBaseInfoVO.getFncScmNm());
			}
			
			if(fncPrjBscInfoVO.getAcXirr() != null) {
				fncPrjBscInfoVO.setAcXirr(fncPrjBscInfoVO.getAcXirr()*100);//转百分数
			}
		}
		return fncPrjBscInfoVO;
	}
	
	/**
	 * 费用信息列表
	 */
	@RequestMapping("/getFncScmChrgParmBigList.do")
	@ResponseBody
	public Object getFncScmChrgParmBigList(Long fncCapPayeeInfoBigId) {

		if(fncCapPayeeInfoBigId == null) return null;
		
		 FncCapPayeeInfoBigVO fncCapPayeeInfoBigVO = fncCapPayeeInfoBigService.selectById(fncCapPayeeInfoBigId);
		 if(fncCapPayeeInfoBigVO != null && fncCapPayeeInfoBigVO.getFncScmChrgParmBigList() != null) {
			 	//设置保证金到期处理方式
				for(FncScmChrgParmBigVO fncScmChrgParmBigVO:fncCapPayeeInfoBigVO.getFncScmChrgParmBigList()){
					if(fncScmChrgParmBigVO.getMrgnUseMtd()!=null && !"".equals(fncScmChrgParmBigVO.getMrgnUseMtd().toString()) && !"null".equals(fncScmChrgParmBigVO.getMrgnUseMtd().toString())){
						List<KeyValueVO> mrgnUseMtdLst = sysDictionaryApiService.getKvList(ScmInfoConstant.FNC_SCM_CHRG_PARM_MRGN_USE_MTD, 
								CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());//保证金使用方式
						for(KeyValueVO kv:mrgnUseMtdLst){
							if(kv.getKey().equals(fncScmChrgParmBigVO.getMrgnUseMtd().toString())){
								fncScmChrgParmBigVO.setMrgnUseMtdDes(kv.getValue());
							}
						}
					}else{
						fncScmChrgParmBigVO.setMrgnUseMtdDes("");
					}
				}
				
		 	Map<String, Object> map = new HashMap<String, Object>();
			map.put("Rows", fncCapPayeeInfoBigVO.getFncScmChrgParmBigList());
			map.put("Total", fncCapPayeeInfoBigVO.getFncScmChrgParmBigList().size());
			return map;
		 }
		 return null;
	}
	
	
	@RequestMapping(value = "/getXIRR.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object getXIRR(HttpServletRequest request, String _fncScmChrgParmBigList) throws Exception {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES);
		String fncPrjId=request.getParameter("prjid");
		
		//1 获取项目信息
		if(fncPrjId == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("fncPrjId为空");
			return result;
		}
		FncPrjBscInfoVO fncPrjBscInfoVO = fncPrjBscInfoService.selectById(Long.valueOf(fncPrjId));
		if(fncPrjBscInfoVO == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("fncPrjBscInfoVO为空");
			return result;
		}
		if(fncPrjBscInfoVO.getAcFiAmt() == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("fncPrjBscInfoVO.getAcFiAmt()为空");
			return result;
		}
		if(fncPrjBscInfoVO.getTranstm() == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("fncPrjBscInfoVO.getTranstm()为空");
			return result;
		}
		
		String acFiAmt = String.valueOf(fncPrjBscInfoVO.getAcFiAmt());//设置实际融资金额
		String fstpyamt;//设置首付款金额
		if(fncPrjBscInfoVO.getFstpyamt() == null) {
			fstpyamt = "0";
		}else {
			fstpyamt = String.valueOf(fncPrjBscInfoVO.getFstpyamt());
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String transtm = sdf.format(fncPrjBscInfoVO.getTranstm());//实际到账日期
		 
		
		//2 获取还款表计划表
		FncPrjPayPlanQueryCondition fncPrjPayPlanQueryCondition = new FncPrjPayPlanQueryCondition();
		fncPrjPayPlanQueryCondition.setProjId(fncPrjBscInfoVO.getId());
		List<FncPrjPayPlanVO> flist1 = this.fncPrjPayPlanService.searchList(fncPrjPayPlanQueryCondition);
		
		
		//3  获取融资端费用信息(历史)
		List<FncPrjPayPlanVO> flist2  = this.fncPrjPayPlanService.selectchgr(fncPrjBscInfoVO.getId());
		if(CollectionUtils.isEmpty(flist2)) {
			flist2 = new ArrayList<FncPrjPayPlanVO>();
		}
		
		//4 新增的融资端费用
		if(StringUtils.isNotBlank(_fncScmChrgParmBigList)) {
			List<FncScmChrgParmBigVO> fncScmChrgParmBigVOList = (List<FncScmChrgParmBigVO>) JsonUtil.toList(_fncScmChrgParmBigList, new FncScmChrgParmBigVO());
			if(CollectionUtils.isNotEmpty(fncScmChrgParmBigVOList)) {
				FncScmChrgParmBigVO fncScmChrgParmBigVO = fncScmChrgParmBigVOList.get(0);
				//是否计入首付款:分期付款并且是保证金,则需要计入融资端费用
				if(fncScmChrgParmBigVO.getCostInTpCd() != null && fncScmChrgParmBigVO.getCostInTpCd().equals(2)
						&& fncScmChrgParmBigVO.getMrgnIs()!= null && fncScmChrgParmBigVO.getMrgnIs().equals(1)) {
					//需要计入融资端费用
					
					FncPrjPayPlanVO fncPrjPayPlanVO = new FncPrjPayPlanVO();
					
					fncPrjPayPlanVO.setCostNm(fncScmChrgParmBigVO.getCostNm());//费用名称
					fncPrjPayPlanVO.setCapital(fncScmChrgParmBigVO.getCostAmt().doubleValue());//费用金额
					fncPrjPayPlanVO.setScmChegId("0");//代表保证金
					
					flist2.add(fncPrjPayPlanVO);
				}
			}
		}
		
		
		
		
		
		
//		List<FncPrjPayPlanVO> flist1 = new ArrayList<FncPrjPayPlanVO>();
//		if (StringUtils.isNotBlank(payplanlist)) {
//			flist1 = JSON.parseArray(payplanlist, FncPrjPayPlanVO.class);
//			
//		}
//		List<FncPrjPayPlanVO> flist2 = new ArrayList<FncPrjPayPlanVO>();
//		if (StringUtils.isNotBlank(fllist)) {
//			flist2 = JSON.parseArray(fllist, FncPrjPayPlanVO.class);
//			
//		}
		List<UpbaaDate> list1= new ArrayList<UpbaaDate>();//repayDate
		UpbaaDate ud0= new UpbaaDate(transtm, -1*(Double.parseDouble(acFiAmt)-Double.parseDouble(fstpyamt)));
		list1.add(ud0);
		Double overcoll=0.00;
		for (FncPrjPayPlanVO vo : flist1) {
			Double paynum=0.00;
			
			if(null!=vo.getRental() && vo.getRental()>0){
			//	paynum+=vo.getRental();
			}
			if(null!=vo.getCapital() && vo.getCapital()>0){
				paynum+=vo.getCapital();
			}
			if(null!=vo.getInterest() && vo.getInterest()>0){
				paynum+=vo.getInterest();
			}
			
			if(null!=vo.getOtherChar() && vo.getOtherChar()>0){
				paynum+=vo.getOtherChar();
			}
			if(null!=vo.getOverColl() && vo.getOverColl()>0){
				paynum+=vo.getOverColl();
				overcoll+=vo.getOverColl();
			}
			UpbaaDate ud= new UpbaaDate(DateUtils.formatDateToString(vo.getRepayDate(), DateUtils.YYYY_MM_DD), paynum);
			int j=0;
			for (int i = 0; i < list1.size(); i++) {
				UpbaaDate tud=list1.get(i);
				if(tud.getDaysFrom1970()<=ud.getDaysFrom1970()){
					j++;
				}else{
					break;
				}
			}
			list1.add(j,ud);
		}
		
		//获取保证金（计入首付）
		FncPrjFstpyInfoQueryCondition qc = new FncPrjFstpyInfoQueryCondition();
		qc.setFncPrjId(fncPrjId);
		double bond = fncPrjFstpyInfoService.getFncPrjFstpyBondAll(qc);
		
		for (FncPrjPayPlanVO vo : flist2) {
			if("0".equals(vo.getScmChegId())){
				if(vo.getCapital() != null) {
					bond= vo.getCapital()/100;
				}
			}
		}
		double bzj=bond+overcoll;//保证金+超额抵押
		List<UpbaaDate> list2= new ArrayList<UpbaaDate>();
		for (int i = list1.size()-1; i>=0; i--) {
			UpbaaDate ud=list1.get(i);
			
			if(bzj-ud.payment>=0 && ud.payment>0){
				bzj=bzj-ud.payment;	
			}else if(bzj-ud.payment<0 && ud.payment>0){
				
				ud.payment=ud.payment-bzj;
				bzj=0;
				list2.add(0, ud);
			}
           if(ud.payment<0){
				list2.add(0, ud);
			}
		}
		
		XirrData Xirr=new XirrData(list2);
		result.setData(Xirr.getXirr());
		return result;
	}
	

	/**
	 * 新增或修改
	 */
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public DataResultVO save(FncCapPayeeInfoBigVO fncCapPayeeInfoBigVO, String _fncScmChrgParmBigList) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		Long id;
		try {
			
			fncCapPayeeInfoBigVO.setFncScmChrgParmBigList(
					(List<FncScmChrgParmBigVO>) JsonUtil.toList(_fncScmChrgParmBigList, new FncScmChrgParmBigVO()));// 合同和支付表明细

			//设置机构名称
			if(fncCapPayeeInfoBigVO.getFundId() != null) {
				FriBaseInfoVO friBaseInfoVO = this.friBaseInfoService.selectById(fncCapPayeeInfoBigVO.getFundId()
						, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
				if(friBaseInfoVO != null) {
					fncCapPayeeInfoBigVO.setFundNm(friBaseInfoVO.getFundRasInsNm());
				}
			}
			
			//设置项目名称 报价
			if(fncCapPayeeInfoBigVO.getFncPrjId() != null) {
				FncPrjBscInfoVO fncPrjBscInfoVO = this.fncPrjBscInfoService.selectById(fncCapPayeeInfoBigVO.getFncPrjId());
				if(fncPrjBscInfoVO != null) {
					fncCapPayeeInfoBigVO.setFncPrjNm(fncPrjBscInfoVO.getFncprjnm());
					fncCapPayeeInfoBigVO.setFncScmId(fncPrjBscInfoVO.getFncscmid());
				}
			}
			
			if (fncCapPayeeInfoBigVO.getId() != null) {
				// 修改
				FncCapPayeeInfoBigVO newFncCapPayeeInfoBigVO = fncCapPayeeInfoBigService
						.selectById(fncCapPayeeInfoBigVO.getId());
				if (newFncCapPayeeInfoBigVO == null) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("信息不存在");
					return result;
				}

				
				fncCapPayeeInfoBigVO.setMdfTm(new Date());
				fncCapPayeeInfoBigVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				fncCapPayeeInfoBigVO.setPayState(newFncCapPayeeInfoBigVO.getPayState());
				fncCapPayeeInfoBigService.modify(fncCapPayeeInfoBigVO);
				id = newFncCapPayeeInfoBigVO.getId();
			} else {
				// 新增
				fncCapPayeeInfoBigVO.setPayState(FncCapPayeeInfoBigConstant.FNC_PAY_STATUS_UNPAY);// 付款状态:未付
				fncCapPayeeInfoBigVO.setIsDel(FncCapPayeeInfoBigConstant.IS_DEL_NO);
				fncCapPayeeInfoBigVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				fncCapPayeeInfoBigVO.setCrtTm(new Date());

				id = fncCapPayeeInfoBigService.add(fncCapPayeeInfoBigVO);
			}
			result.setData(id);// 返回id
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, null, "操作数据失败.DATA:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 发起申请流程
	 */
	@RequestMapping(value = "/startFlow.do")
	@ResponseBody
	public Object startFlow(Long id, String operate) {

//		String procDefKey="FLOW_0000_R023_001";

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if (StringUtils.isEmpty(id)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, null, SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY,
					CurrentThreadContext.getCurrentUserName());
			return result;
		}

		FncCapPayeeInfoBigVO newFncCapPayeeInfoBigVO = fncCapPayeeInfoBigService.selectById(id);
		if (newFncCapPayeeInfoBigVO == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("账户信息不存在");
			return result;
		}
		/**
		 * 发起流程
		 */
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			// 流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setBusinessKey(String.valueOf(id));
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(FriBaseInfoConstant.REF_FLOW_S_H_FRI);
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);// 优先级,可以在界面定义
			flowStartParamsDTO.setBusinessType(FncCapPayeeInfoBigConstant.FLOW_MODEL_TYP_BIG);// TODO
																			// 确认用不用
			flowStartParamsDTO.setModelTyp(FncCapPayeeInfoBigConstant.FLOW_MODEL_TYP_BIG);// 需要和流程配置中的模块类型匹配
//			if ("openAccount".equals(operate)) {
//				// 集团账户开户流程
//				flowStartParamsDTO.setModelTyp(FncCapPayeeInfoBigConstant.FLOW_MODEL_TYP_OPEN_ACCOUNT);// 需要和流程配置中的模块类型匹配
//			} else {
//				// 集团账户销户流程
//				flowStartParamsDTO.setModelTyp(FncCapPayeeInfoBigConstant.FLOW_MODEL_TYP_CLOSE_ACCOUNT);
//			}

			// 设置关键字 开始
			StringBuffer keyWords = new StringBuffer();

			flowStartParamsDTO.setSearchDesc(keyWords.toString());
			BaseLogUtils.info(logger, "borrowApplyStartFlow", "keyWords：" + keyWords.toString(),
					CurrentThreadContext.getCurrentUserName());
			// 设置关键字 结束

			Map<String, Object> startParams = new HashMap<String, Object>();
			startParams.put("originator", "noManager");// 默认非客户经理(noManager)
			startParams.put("payType", newFncCapPayeeInfoBigVO.getPayType());
			startParams.put("id", newFncCapPayeeInfoBigVO.getId());
			flowStartParamsDTO.setStartParams(startParams);

			DataResultDTO dataResultDTO = this.fncCapPayeeInfoBigService.addFlowStart(flowStartParamsDTO);
			if (!dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
			}
			if (null != dataResultDTO && null != dataResultDTO.getData()) {
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
				if (StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
					result.setInfo("下一个节点操作人:" + flowStartedDTO.getNextOperUsrNames());
				} else {
					result.setInfo("流程发起成功");
				}
				//流程发起成功，更改状态
				newFncCapPayeeInfoBigVO.setFlowUser(CurrentThreadContext.getCurrentUserName());
				newFncCapPayeeInfoBigVO.setPayState(FncCapPayeeInfoBigConstant.FNC_PAY_STATUS_PAYING);
				newFncCapPayeeInfoBigVO.setpNo(flowStartedDTO.getProcInstanceNo());
				newFncCapPayeeInfoBigVO.setSendSt("sendWait");//待发送
				fncCapPayeeInfoBigService.modify(newFncCapPayeeInfoBigVO);
			}
			

		} catch (BaseException e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(e.getMessage());
			BaseLogUtils.info(logger, null, "错误[BaseException],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO)
					+ " -ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, null,
					"错误[Exception],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" + e.getMessage(),
					CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		}
		return result;
	}
	/**
	 * 跳转到新增或修改页面
	 */
	@RequestMapping(value = "/getFlow.do")
	public Object getFlow(HttpServletRequest request) {
		String flag = (String) request.getParameter("flag");
		if ("003".equals(flag)) {//
			request.setAttribute("operate", "update");

			//计费信息-保证金到期处理方式
			List<KeyValueVO> mrgnUseMtdLst = sysDictionaryApiService.getKvList(ScmInfoConstant.FNC_SCM_CHRG_PARM_MRGN_USE_MTD, 
					CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
			request.setAttribute("mrgnUseMtdJSON",JSONObject.toJSONString(mrgnUseMtdLst));
			
			//计费信息-费用名称列表
			List<KeyValueVO> feeList = sysDictionaryApiService.getKvList(ScmInfoConstant.FNC_SCM_FEE, 
					CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
			request.setAttribute("feeListJSON", JSONObject.toJSONString(feeList));
			
		}else {
			request.setAttribute("operate", "view");

		}
		
		// 付款类型(数据字典)
		request.setAttribute("payTypeList", sysDictionaryApiService.getKvList(FncCapPayeeInfoBigConstant.FNC_PAY_TYPE,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

		// 付款账户(数据字典)
		request.setAttribute("payerAccNoList", sysDictionaryApiService.getKvList(FncCapPayeeInfoBigConstant.FNC_PAYER_ACCNO,
				CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd()));

		String id = (String) request.getParameter("aid");
		if (StringUtils.isNotBlank(id)) {
			request.setAttribute("fncCapPayeeInfoBigVO", fncCapPayeeInfoBigService.selectById(Long.valueOf(id)));
		}
		request.setAttribute("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		request.setAttribute("loginUsrNm", CurrentThreadContext.getCurrentUserName());
		String  taskNm= request.getParameter("taskNm");//任务名称
		if("出纳付款".equals(taskNm)) {
			request.setAttribute("tabFlag", "101");// 出纳付款
			return "rfbase/fncCapPayeeInfobig/fncCapPayeeInfoBigPay"; 
		}
		return "rfbase/fncCapPayeeInfobig/fncCapPayeeInfoBigSave";
	}
	/**
	 * 出纳付款发送拜特网银接口
	 * @author gengchunlan
	 */
	@RequestMapping(value = "/sendPay.do")
	@ResponseBody
	public Object sendPay(HttpServletRequest request) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String id =  request.getParameter("id");
		if(StringUtils.isEmpty(id)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("账户信息主键id不存在");
			return result;
		}
		FncCapPayeeInfoBigVO fncCapPayeeInfoBigVO = fncCapPayeeInfoBigService.selectById(Long.parseLong(id));
		if (fncCapPayeeInfoBigVO == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("账户信息不存在");
			return result;
		}
		FncCapPayeeInfoBigVO fncCapPayeeInfoBig =new FncCapPayeeInfoBigVO();
		fncCapPayeeInfoBig.setId(Long.parseLong(id));
		fncCapPayeeInfoBig.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		DataResultDTO  resultDTO =new DataResultDTO(BaseConstant.IS_YESNO_NO, SysLogConstant.LOG_CMM_OPERATE_FAIL);
		if("sendWait".equals(fncCapPayeeInfoBigVO.getSendSt()) || "sendFailure".equals(fncCapPayeeInfoBigVO.getSendSt())
				|| "payFailure".equals(fncCapPayeeInfoBigVO.getSendSt()) || "cancelled".equals(fncCapPayeeInfoBigVO.getSendSt())) {
			BigDecimal payAmt = fncCapPayeeInfoBigVO.getPayAmt();
			if(payAmt.compareTo(new BigDecimal("0"))>0) {
				if(validateFncCapPayee(fncCapPayeeInfoBigVO)) {//校验必填项
					//更新为发送中
					fncCapPayeeInfoBig.setMdfTm(new Date());
					fncCapPayeeInfoBig.setSendSt("sending");
					fncCapPayeeInfoBigService.updatePayerAcc(fncCapPayeeInfoBig);
					try {
						resultDTO=fncCapPayeeInfoBigService.sendPay(fncCapPayeeInfoBigVO);
					}catch(Exception e) {
						resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
						resultDTO.setInfo("发送失败！");
						logger.error("发送失败！", e);
					}
				}else {
					resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
					resultDTO.setInfo("信息不完整，无法发送！");
					BaseLogUtils.info(logger, "sendPay", id+"sendPay信息不完整，无法发送" );
				}
			}else {//金额为0直接付款成功
				fncCapPayeeInfoBig.setMdfTm(new Date());
				fncCapPayeeInfoBig.setSendSt("paySuccess");
				fncCapPayeeInfoBigService.updatePayerAcc(fncCapPayeeInfoBig);
			}
		}
		return resultDTO; 	
	}
	/**
	 * 网银付款记录查询接口
	 * @author gengchunlan
	 */
	@RequestMapping(value = "/getPaymentById.do")
	@ResponseBody
	public Object getPaymentById(HttpServletRequest request) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String id =  request.getParameter("id");
		if(StringUtils.isEmpty(id)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("账户信息主键id不存在");
			return result;
		}
		FncCapPayeeInfoBigVO fncCapPayeeInfoBigVO = fncCapPayeeInfoBigService.selectById(Long.parseLong(id));
		if (fncCapPayeeInfoBigVO == null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("账户信息不存在");
			return result;
		}
		BaseLogUtils.info(logger, "getPaymentById", "网银付款记录查询" + fncCapPayeeInfoBigVO);
		fncCapPayeeInfoBigVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());//设置变更人
		FncCapPayeeInfoBigVO bigDto=fncCapPayeeInfoBigService.callPaymentQuery(fncCapPayeeInfoBigVO);
		BaseLogUtils.info(logger, "getPaymentById", "网银付款记录查询bigDto"+JSON.toJSONString(bigDto));
		result.setInfo("操作成功!");
		return result; 	
	}
	/**
	 * 校验必填项
	 * @author gengchunlan
	 */
	private boolean validateFncCapPayee(FncCapPayeeInfoBigVO fncCapPayeeInfoBigVO ) {
		boolean result=true;
		//校验必填项
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getpNo())) {//流程实例编号
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getAccNo())) {//收款方账号
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getRcptUnt())) {//收款方名称
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPayeeBkNm())) {//收款方银行
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPayeeBkNo())) {//收款方银行号（fls与bfs预先约定）
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPayAmt().longValue())) {//付款金额(单位：分)
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPubPri())) {//对公对私（1:对私 0：对公）	Y
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPayer())) {//付款方, 自动付款必填	C
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPayerAccNo())) {//付款方账号, 自动付款必填	C
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPayerBkNm())) {//付款方银行, 自动付款必填	C
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getPayerBkNo())) {//付款方银行代码(我司与拜特预先预定) , 自动付款必填	C
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getCorpCode())) {//单位编码
			result=false;
		}
		if(StringUtils.isEmpty(fncCapPayeeInfoBigVO.getItemCode())) {//预算科目	
			result=false;
		}
		return result;
	}
	/**
	 * 出纳付款节点修改账号信息
	 */
	@RequestMapping(value = "/updatePayerAcc.do")
	@ResponseBody
	public DataResultVO updatePayerAcc(HttpServletRequest request, HttpServletResponse response) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		BaseLogUtils.info(logger, "updatePayerAcc", "出纳付款节点修改账号信息===");
		String id =  request.getParameter("id");
		String payer = request.getParameter("payer");
		String payerAccNo = request.getParameter("payerAccNo");
		String payerBkNm = request.getParameter("payerBkNm");
		String payerBkNo = request.getParameter("payerBkNo");
		String feeType	 = request.getParameter("feeType");
		String type	 = request.getParameter("type");
		String payerMain	 = request.getParameter("payerMain");
		
		BaseLogUtils.info(logger, "updatePayerAcc", "出纳付款节点修改账号信息===id"+id);
		try {
			if(StringUtils.isNotBlank(id)) {
				FncCapPayeeInfoBigVO  bigVo = new FncCapPayeeInfoBigVO();
				bigVo.setId(Long.parseLong(id));
				bigVo.setMdfTm(new Date());
				bigVo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				bigVo.setPayer(payer);//付款方
				bigVo.setPayerAccNo(payerAccNo);//付款方银行账号
				bigVo.setPayerBkNm(payerBkNm);//付款方开户行
				bigVo.setPayerBkNo(payerBkNo);//付款方开户行行号
				bigVo.setFeeType(feeType);//费用种类
				bigVo.setType(type);//费用种类
				bigVo.setPayerMain(payerMain);//付款公司主体（FNC0011）
				fncCapPayeeInfoBigService.updatePayerAcc(bigVo);
			}
			result.setData(id);// 返回id
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, null, "操作数据失败.DATA:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	
	
	/**
	 * 删除
	 */
	@RequestMapping(value = "/removeById.do")
	@ResponseBody
	public DataResultVO removeById(Long id) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		try {
			if (id != null) {
				FncCapPayeeInfoBigVO fncCapPayeeInfoBigVO = fncCapPayeeInfoBigService.selectById(id);
				if (fncCapPayeeInfoBigVO == null) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("信息不存在,id:"+id);
					return result;
				}

				FncCapPayeeInfoBigVO newFncCapPayeeInfoBigVO = new FncCapPayeeInfoBigVO();
				newFncCapPayeeInfoBigVO.setId(id);
				newFncCapPayeeInfoBigVO.setMdfTm(new Date());
				newFncCapPayeeInfoBigVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				newFncCapPayeeInfoBigVO.setIsDel(FncCapPayeeInfoBigConstant.IS_DEL_YES);
				fncCapPayeeInfoBigService.modify(newFncCapPayeeInfoBigVO);
			} 
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, null, "操作数据失败.DATA:" + ex.getMessage(),
					CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
}
